import React, { useState } from 'react';

function Video() {
    // 获取已有的视频 URL
    let existingUrlsString = localStorage.getItem('url');
    let existingUrls = existingUrlsString? existingUrlsString.split(',') : [];

    const [selectedVideos, setSelectedVideos] = useState([]);
    const [isAllSelected, setIsAllSelected] = useState(false);

    // 全选或取消全选
    const handleSelectAll = () => {
        if (isAllSelected) {
            setSelectedVideos([]);
        } else {
            setSelectedVideos(existingUrls.filter(url => url.endsWith('.mp4') || url.endsWith('.avi') || url.endsWith('.mov')));
        }
        setIsAllSelected(!isAllSelected);
    };

    // 单选
    const handleSingleSelect = (url) => {
        if (selectedVideos.includes(url)) {
            setSelectedVideos(selectedVideos.filter(item => item!== url));
        } else {
            setSelectedVideos([...selectedVideos, url]);
        }
    };

    // 反选
    const handleInverseSelect = () => {
        const allVideos = existingUrls.filter(url => url.endsWith('.mp4') || url.endsWith('.avi') || url.endsWith('.mov'));
        const newSelected = allVideos.filter(url =>!selectedVideos.includes(url));
        setSelectedVideos(newSelected);
    };

    // 删除选中的视频
    const deleteSelectedVideos = () => {
        const updatedUrls = existingUrls.filter(url =>!selectedVideos.includes(url));
        localStorage.setItem('url', updatedUrls.join(','));
        setSelectedVideos([]);
        setIsAllSelected(false);
    };

    return (
        <div>
            <div>
                <input type="checkbox" checked={isAllSelected} onChange={handleSelectAll} />全选
                <button onClick={handleInverseSelect}>反选</button>
                <button onClick={deleteSelectedVideos}>删除选中</button>
            </div>
            {existingUrls.map((url, index) => {
                if (url.endsWith('.mp4') || url.endsWith('.avi') || url.endsWith('.mov')) {
                    return (
                        <div key={index}>
                            <video width="300" controls>
                                <source src={url} type={`video/${url.split('.').pop()}`} />
                                Your browser does not support the video tag.
                            </video>
                            <input
                                type="checkbox"
                                checked={selectedVideos.includes(url) || isAllSelected}
                                onChange={() => handleSingleSelect(url)}
                            />
                        </div>
                    );
                } else {
                    return null;
                }
            })}
        </div>
    );
}

export default Video;